package com.alphas.openapiinterface.controller;

import com.alphas.openapiclientsdk.model.User;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api")
public class ApiController {
    //todo从数据库中读取accessKey
    // 模拟数据库存储的密钥对
    private static final Map<String, String> KEY_STORE = new HashMap<>();

    static {

        KEY_STORE.put("Alphas", "abcdefg"); // accessKey: Alphas, secretKey: abcdefg
    }

    // 用于nonce校验的缓存，需定时清理过期数据（此处简化为每次校验时清理）
    private static final Map<String, Long> nonceCache = new HashMap<>();
    private static final long MAX_TIMESTAMP_DIFF = 300; // 5分钟（单位：秒）

    @GetMapping("/name")
    public String getName(String name) {
        System.out.println(name);
        return name;
    }

    @PostMapping("/name")
    public String postName(@RequestParam String name) {
        System.out.println("post" + name);
        return name;
    }

    @PostMapping("/name/user")
    public String postUserName(@RequestBody User user, HttpServletRequest request) {
        String accessKey = request.getHeader("accessKey");
        String body = request.getHeader("body");
        String decodedBody = null;
        try {
            decodedBody = new String(body.getBytes("ISO-8859-1"), "UTF-8");
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
        String timestamp = request.getHeader("timestamp");
        String nonce = request.getHeader("nonce");
        String sign = request.getHeader("sign");
        cheakSign(accessKey, nonce, timestamp, body, sign, decodedBody);

        String name = user.getName();
        //统计次数加1
        return name;
//        if (!accessKey.equals("Alphas")){
//            throw new RuntimeException("无权限");
//        }
//        if (System.currentTimeMillis()/1000 - timestamp < 5 ){
//
//        }
//        String name = user.getName();
//        System.out.println(name);
//        return name;
    }

    private boolean cheakSign(String accessKey, String nonce, String timestamp, String body, String sign, String decodedBody) {
        // 1. 基本参数校验
        if (anyEmpty(accessKey, body, timestamp, nonce, sign)) {
            throw new RuntimeException("请求头参数缺失");
        }
        // 2. 校验accessKey有效性
//        String secretKey = KEY_STORE.get(accessKey);
//        if (secretKey == null) {
//            throw new RuntimeException("无效的accessKey");
//        }
        // 3. 校验时间戳有效性
        long currentTime = System.currentTimeMillis() / 1000;
        long requestTime = Long.parseLong(timestamp);
        if (Math.abs(currentTime - requestTime) > MAX_TIMESTAMP_DIFF) {
            throw new RuntimeException("请求已过期");
        }
        // 4. 校验nonce唯一性
        synchronized (nonceCache) {
            if (nonceCache.containsKey(nonce)) {
                throw new RuntimeException("重复的请求");
            }
            nonceCache.put(nonce, currentTime);
            // 清理过期nonce（超过5分钟）
            nonceCache.entrySet().removeIf(entry -> currentTime - entry.getValue() > MAX_TIMESTAMP_DIFF);
        }
        // 5. 生成服务端签名
//        Digester sha256 = new Digester(DigestAlgorithm.SHA256);
//        String serverSign = sha256.digestHex(decodedBody + "." + secretKey);
//        System.out.println("这是服务端的签名" + serverSign);
        // 6. 校验签名
//        if (!serverSign.equals(sign)) {
//            throw new RuntimeException("签名验证失败");
//        }
        return true;
    }
    //todo 调用次数+1 invokeCount

    // 辅助方法：检查任意参数为空
    private boolean anyEmpty(String... params) {
        return Arrays.stream(params).anyMatch(p -> p == null || p.trim().isEmpty());
    }
}
